// 云对象教程: https://uniapp.dcloud.net.cn/uniCloud/cloud-obj
// jsdoc语法提示教程：https://ask.dcloud.net.cn/docs/#//ask.dcloud.net.cn/article/129
const {
	userName,
	userAvatar
} = require("./userInfo");
const send = require('../requestReturn')
const db = uniCloud.database();
module.exports = {
	_before: function() {},

	// 获取用户头像、名称
	getUserInfo: async function(openid) {
		if (!openid) {
			return {
				RectCode: -1, //'OPPENID_IS_NULL'
				RetMessage: '用户openid不能为空'
			}
		}

		const {
			data
		} = await db.collection('user').where({
			userID: openid
		}).get()

		let result = null
		// 使用Math.random()和Math.floor()来从原数组中随机选择一个元素
		const randomIndex = Math.floor(Math.random() * 8);
		if (data.length) {
			const {
				fileList
			} = await uniCloud.getTempFileURL({
				fileList: [data[0].avatarID]
			})
			result = {
				...data[0],
				avatarURL: fileList[0].tempFileURL
			}
		} else {
			const {
				fileList
			} = await uniCloud.getTempFileURL({
				fileList: [userAvatar[randomIndex]]
			})
			const params = {
				userID: openid,
				name: userName[randomIndex],
				avatarID: fileList[0].fileID,
			}
			db.collection('user').add(params)
			result = {
				...params,
				avatarURL: fileList[0].tempFileURL
			}
		}

		// 返回结果
		return send(result)
	},

	updateUserInfo: async function(params = {}) {
		const {
			data
		} = await db.collection('user').where({
			userID: params.userID
		}).get()

		if (data.length) {
			const userInfo = data[0]
			for (let key in params) {
				userInfo[key] = params[key]
			}
			await db.collection('user').where({
				userID: params.userID
			}).update(userInfo)
			return 'ok'
		}
	},

}